<template>
  <div>
    <form
      id="fileUploadF"
      ref="fileUploadF"
      :action="action"
      method="post"
      target="formUpFile"
      class="form form-group text-right"
      enctype="multipart/form-data"
    >
      <div class="filInput">
        <template v-if="$slots.fileBtn">
          <slot name="fileBtn"></slot>
        </template>
        <template v-else>
          <div
            style="width: 400px;"
            :style="propStyle"
          >
            <el-input
              v-model="fileName"
              placeholder="请选择文件"
            >
              <template slot="append">
                <span class="el-icon-more" />
              </template>
            </el-input>
          </div>
        </template>
        <template v-for="(vo, key) in formData">
          <input
            :key="`${key}_${vo}`"
            type="hidden"
            :name="key"
            :value="vo"
          >
        </template>
        <template v-if="multiple">
          <input
            ref="fileUpIpt"
            type="file"
            class="fileUpIpt form-inline"
            :accept="accept"
            name="file"
            multiple="multiple"
            @change="getInput"
          >
        </template>
        <template v-else>
          <input
            ref="fileUpIpt"
            type="file"
            class="fileUpIpt form-inline"
            :accept="accept"
            name="file"
            @change="getInput"
          >
        </template>
        <!--<el-button type="primary">
          {{ title?title:'上传附件' }}
        </el-button>-->
      </div>
    </form>
    <!--<div v-if="fileList.length" class="fileList">
      <ul class="el-upload-list el-upload-list--text">
        <li v-for="(el,index) in fileList" :tabindex="index" class="el-upload-list__item is-success">
          <a class="el-upload-list__item-name"><i class="el-icon-document" />{{ el.name }}</a>
          <label class="el-upload-list__item-status-label">
            <i class="el-icon-upload-success el-icon-circle-check" />
          </label>
          <i class="el-icon-close" @click="handleRemove(index)" /><i class="el-icon-close-tip" />
        </li>
      </ul>
    </div>-->
    <iframe
      ref="formUpFile"
      border="none"
      width="0"
      height="0"
      name="formUpFile"
      @load="iframeLoad()"
    />
  </div>
</template>
<script>
// 使用vnode时，获取不到this.$store和this.$router
import store from '@/store'
import router from '@/router'
export default {
  props: {
    action: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    // 上传样式
    propStyle: {
      type: Object,
      default() {
        return {}
      }
    },
    // 上传时传递的数据
    formData: {
      type: Object,
      default() {
        return {}
      }
    },
    successMsg: {
      type: String,
      default: ''
    },
    //excel文件获取校验
    excelaccept: {
      type: Boolean,
      default: false
    },
    // 是否自动上传
    autoUpload: {
      type: Boolean,
      default: false
    },
    // 是否多文件上传，不支持ie9
    multiple: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      default: '*/*'
    },
    // 上传前校验
    beforeUpload: {
      type: Function,
      default: () => {
        return true
      }
    },
    // 选择文件后检验文件数量
    filesSizeCheck: {
      type: Function,
      default: () => {
        return true
      }
    }
  },
  data() {
    return {
      fileList: [],
      IE: false,
      fileName: ''
    }
  },
  mounted() {
    this.ifIE()
  },
  methods: {
    // 获取上传文件
    getInput() {
      // const file = document.getElementById('fileUpIpt')
      const file = this.$refs.fileUpIpt;
      let fileType = file.value.substr(file.value.lastIndexOf("."));
      if(this.excelaccept && ".xls" != fileType && ".xlsx" != fileType ){
	        this.$message({
	          type: 'error',
	          message: '导入模板文件！'
	        })	
	        this.fileName =''
	        this.$refs.fileUpIpt.value='';
	        return ; 
      }
      if (file.files) {
        let str = ''
        for (let i = 0; i < file.files.length; i++) {
          str += `${file.files[i].name}/`
        }
        this.fileName = str.slice(0, -1)
      } else {
        const arr = file.value.split('\\')
        this.fileName = arr[arr.length - 1]
      }

      if (this.autoUpload) {
        this.inputChange()
      }
    },
    upload() {
      const file = this.$refs.fileUpIpt
      if (!file.files.length) {
        return
      }
      for (let i = 0; i < file.files.length; i++) {
        const item = file.files[i]
        const flag = this.beforeUpload(item)
        if (flag) {
          this.uploadFunc({
            file: item
          })
        } else {
//        this.fileName = ''
//        this.$refs.fileUpIpt.value = ''
        }
      }
    },
    /**
     * @name uploadFunc
     * @description 文件上传方法
     * @author cjs1992
     * @date 2019-09-25 10:32:33
     */
    uploadFunc(param) {
      const { file } = param
      const data = new FormData()
      for (const key in this.formData) {
        data.append(key, this.formData[key])
      }
      data.append('file', file, file.name)
      const xhr = new XMLHttpRequest()
      xhr.open('post', this.action, true)
      xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
      // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
      xhr.send(data)
      try {
        this.$store.dispatch('common/setReqNum', 1);
        this.$store.dispatch('common/setReqType', 1);
      } catch (error) {
        store.dispatch('common/setReqNum', 1);
        store.dispatch('common/setReqType', 1);
      }
      xhr.onreadystatechange = () => {
        try {
          this.$store.dispatch('common/setReqNum', -1);
        } catch (error) {
          store.dispatch('common/setReqNum', -1);
        }
        if (xhr.readyState === 4) {
          const res = JSON.parse(xhr.response)
          if (xhr.status === 200) {
            // const res = JSON.parse(xhr.response)
            if (res.status === 1000) {
                this.$message({
                  type: 'success',
                  message: this.successMsg || res.msg
                })
                this.$emit('success', res)          	
              //			          return xhr.responseText
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
  //        this.$refs.fileUpIpt.value = ''
            return xhr.responseText
          } else {
            if (xhr.status === 403) {
              this.$message({
                type: 'warning',
                message: '登录失效，请重新登录!'
              });
              try {
                if (window.$loginUrl) {
                  window.$toLoginFunc()
                } else {
                  this.$router.push({
                    path: '/login'
                  });
                }
              } catch (error) {
                if (window.$loginUrl) {
                  window.$toLoginFunc()
                } else {
                  router.push({
                    path: '/login'
                  });
                }
              }
            } else {
              this.$message({
                type: 'warning',
                message: res.message
              });
              this.$emit('uploadError');
            }
          }
        }
      }
    },
    // 删除
    handleRemove(index) {
      this.fileList.splice(index, 1)
      this.$emit('sendMessageTop', this.fileList)
    },
    // 触发file
    inputChange() {
      if (this.IE) {
        // IE9
        if (!this.filesSizeCheck()) {
          return;
        }
        const arr = this.fileName.split('.')
        const flag = this.beforeUpload({
          type: arr[arr.length - 1],
          name: this.fileName
        })
        if (flag) {
          this.$refs.fileUploadF.submit()
        } else {
          this.fileName = ''
          this.$refs.fileUpIpt.value = ''
        }
      } else {
        // 非IE9浏览器
        this.filesSizeCheck(this.$refs.fileUpIpt.files) ? this.upload() : null
      }
    },
    // 获取iframe内容
    iframeLoad(ifame) {
      const _this = this
      setTimeout(function() {
        // 当使用vnode时，此处会出现为undefined的情况
        if (_this.$refs.formUpFile === undefined) {
          return;
        }
        const res = _this.$refs.formUpFile.contentWindow.document
        let data
        if (res.body.innerHTML) {
          try {
            data = JSON.parse(res.body.innerHTML)
          } catch (error) {
            // 不是json数据，http错误，处理http错误
            return
          }
        } else {
          return
        }
        if (data.status === 1000) {
          _this.$message({
            type: 'success',
            message: this.successMsg || data.msg
          })        	
          _this.$emit('success', data.data)
        } else {
          _this.$message({
            type: 'error',
            message: data.msg
          })
        }
        res.body.innerHTML = ''
      }, 100)
    },
    // 判断是否为IE9
    ifIE() {
      var browser = navigator.appName
      var b_version = navigator.appVersion
      var version = b_version.split(';')
      var trim_Version = version[1].replace(/[ ]/g, '')
      if (
        browser === 'Microsoft Internet Explorer' &&
        trim_Version === 'MSIE9.0'
      ) {
        this.IE = true
      }
    }
  }
}
</script>
<style scoped="scoped">
.el-input-group {
  line-height: normal;
  display: inline-table;
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
}
.fileUpIpt {
  opacity: 0;
  position: absolute;
  left: 0;
  top: 0px;
  bottom: 0;
  height: 100%;
  width: 100%;
}
.filInput {
  width: auto;
  height: 36px;
  display: inline-block;
  position: relative;
}
.fileList {
  padding: 20px;
}
.file-uploads {
  overflow: hidden;
  position: relative;
  text-align: center;
  display: inline-block;
}

.file-uploads.file-uploads-html4 input,
.file-uploads.file-uploads-html5 label {
  background: #fff;
  opacity: 0;
  font-size: 20em;
  z-index: 1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  position: absolute;
  width: 100%;
  height: 100%;
}

.file-uploads.file-uploads-html4 label,
.file-uploads.file-uploads-html5 input {
  background: rgba(255, 255, 255, 0);
  overflow: hidden;
  position: fixed;
  width: 1px;
  height: 1px;
  z-index: -1;
  opacity: 0;
}
</style>
